/**
 * @file 菜单管理
 * @date 2025/09/01 16:03:53
 * @author lyqjob@yeah.net
 */

import { useState, useEffect } from 'react';
import { Table, Tag, Space, Button, Modal, Form, Input, Radio, Col, Row, message, Select } from 'antd';
import IconPicker from '@/components/IconPicker';
// 导入公共的Icon映射表
import { IconMap } from '@/utils/iconUtils';
import { adminApi } from "@/services/admin";
import AuthButton from '@/components/AuthButton';
import { useSelector } from 'react-redux';
import dayjs from '@/utils/dayjs.js';

const { Option } = Select;

const Menulist = () => {
    const [form] = Form.useForm();
    const [open, setOpen] = useState(false);
    const [parent, setParent] = useState({});
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true)
    const [nodetype, setNodeType] = useState(1);
    const [visible, setVisible] = useState(false);
    const [selectedIcon, setSelectedIcon] = useState('');
    

    const userInfo = useSelector(state => state.global.userInfo)

    // 统一提示
    const clickTip = () => {
        message.warning('开发中，暂不可操作')
    }

    const columns = [
        { title: '菜单名称', dataIndex: 'name', key: '', width: 170, fixed: 'left' },
        {
            title: '类型', dataIndex: 'node_type', key: '', width: 100,
            render: (tag) => {
                return (
                    <Tag color={tag === 1 ? 'gold' : tag   === 2 ? 'green' : 'red'} key={tag}>
                        {tag === 1 ? '目录' : tag === 2 ? '菜单' : '子页面'}
                    </Tag>
                )
            }
        },
        {
            title: '图标',
            dataIndex: 'icon',
            key: '',
            width: 100,
            render: (icon) => {
                return (
                    IconMap[icon]
                )
            }
        },
        { title: '排序', dataIndex: 'sort', key: '', width: 100 },
        { title: '模块编码', dataIndex: 'module_code', key: '', width: 150 },
        { title: '权限编码', dataIndex: 'permission_code', key: '', width: 150 },
        { title: '路由', dataIndex: 'route_path', key: '', width: 150 },
        { title: '组件路径', dataIndex: 'component_path', key: '', width: 150 },
        {
            title: '系统预制', dataIndex: 'is_system', key: '', width: 100,
            render: (tag) => {
                return (
                    <Tag color={tag === 1 ? 'gold' : 'green'} key={tag}>
                        {tag === 1 ? '是' : '否'}
                    </Tag>
                )
            }
        },
        {
            title: '是否展示', dataIndex: 'is_show', key: '', width: 100,
            render: (tag) => {
                return (
                    <Tag color={tag === 1 ? 'gold' : 'green'} key={tag}>
                        {tag === 1 ? '是' : '否'}
                    </Tag>
                )
            }
        },
        {
            title: '访问类型', dataIndex: 'access_type', key: '', width: 100,
            render: (tag) => {
                return (
                    <Tag color={tag === 0 ? 'green' : 'gold'} key={tag}>
                        {tag === 0 ? '公开' : '角色授权'}
                    </Tag>
                )
            }
        },

        {
            title: '创建时间', dataIndex: 'created_at', key: '', width: 200,
            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '操作',
            dataIndex: '',
            key: 'options',
            width: 100,
            fixed: 'right',
            render: (item) => {
                return (
                    <Space >
                        {item.node_type !== 3 && item.is_system === 0 ?
                            <AuthButton permission={['menu:create']}>
                                <a
                                    onClick={() => {
                                        message.warning('暂不可操作')
                                        return
                                        // 文件夹添加文件夹或页面
                                        if (item.node_type === 1) {
                                            setParent(item)
                                            setNodeType(2)
                                            setOpen(true)
                                        }
                                        // 页面增加子页面
                                        if (item.node_type === 2) {
                                            setParent(item)
                                            setNodeType(3)
                                            setOpen(true)
                                        }
                                    }}>增加</a>
                            </AuthButton>
                            : null}

                        {
                             item.is_system === 0 ?
                                <AuthButton permission={['menu:delete']}>
                                    <a onClick={()=>onDelete(item.id)}>删除</a>
                                </AuthButton>
                                : null
                        }
                    </Space>
                )
            }

        },
    ];

    // 删除菜单
    const onDelete = async (id) => {
        const [err, res] = await adminApi.deleteMenu(id)
        if (err) {
            // message.error('删除失败')
        }
        if (res) {
            message.success('删除成功')
            getList()
        }

    }



    // 创建菜单
    const onCreate = async values => {
        const [err, res] = await adminApi.createMenu(values)
        if (err) {
            message.error('添加失败')
        }
        if (res) {
            message.success('添加成功')
            setOpen(false)
            setSelectedIcon('')
            getList()
        }

    };

    useEffect(() => {
        getList()
    }, [])

    // 获取菜单列表
    const getList = async () => {

        const [err, result] = await adminApi.getMenuTree();
        if (err) {
            message.error('获取菜单列表失败')
        }
        if (result) {
            setLoading(false)
            setData(result.data)

            window.process.done();
        }

    }


    // 切换
    const changeRadio = (eve) => {
        const value = eve.target.value;
        setNodeType(value)
    }


    // 选择图标
    const selectIcon = (icon) => {
        setSelectedIcon(icon)
    }




    return (
        <div className="container">
            <AuthButton permission={['menu:create']}>
                <Button onClick={() => {
                    setNodeType(2)
                    setOpen(true)
                    // message.warning('暂不可操作') 
                }} type="primary" style={{ marginBottom: 16 }}>
                    添加菜单
                </Button>
            </AuthButton>

            <Table
                columns={columns}
                loading={loading}
                rowKey={'id'}
                pagination={false}
                scroll={{ x: 1500 }}
                // expandable={{
                //   expandedRowRender: record => <p style={{ margin: 0 }}>{record.description}</p>,
                //   rowExpandable: record => record.name !== 'Not Expandable',
                // }}
                dataSource={data}
            />
            <Modal
                open={open}
                title="添加菜单"
                okText="确定"
                cancelText="取消"
                width={800}
                okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
                onCancel={() => {
                    setOpen(false)
                    setSelectedIcon('')
                }}
                destroyOnHidden
                modalRender={dom => (
                    <Form
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        layout="horizontal"
                        form={form}
                        name="form_in_modal"
                        initialValues={{ node_type: nodetype, parent_name: parent?.name, parent_id: parent?.id, is_show: 1, access_type: 1, icon: selectedIcon }}
                        clearOnDestroy
                        onFinish={values => onCreate(values)}
                        style={{ maxWidth: 1200 }}

                    >
                        {dom}
                    </Form>
                )}
            >
                <Row>
                    <Col span={8} >
                        <Form.Item
                            name="parent_id"
                            label="父节点id"
                            hidden={true}
                        >
                            <Input disabled={true} />
                        </Form.Item>
                        <Form.Item
                            name="parent_name"
                            label="父节点"
                        >
                            <Input disabled={true} />
                        </Form.Item>
                    </Col>

                    <Col span={12} >
                        <Form.Item
                            name="node_type"
                            label="节点类型"
                            rules={[{ required: true, message: '请选择节点类型' }]}>

                            <Radio.Group onChange={changeRadio} disabled={parent.id && nodetype === 3 ? true : false}>
                                <Radio value={1}>目录</Radio>
                                <Radio value={2}>页面</Radio>
                                {
                                    parent?.id && parent?.node_type === 1 ? null :
                                        <Radio value={3}>子页面</Radio>
                                }
                            </Radio.Group>
                        </Form.Item>
                    </Col>


                </Row>
                <Row>
                    <Col span={8} >
                        <Form.Item
                            name="module_code"
                            label="模块编码"
                            rules={[{ required: true, message: '请添加模块编码' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={16} >
                        <Space.Compact style={{width:'100%'}}>
                            <Form.Item
                                style={{width:'80%'}}
                                labelCol={{ span: 5 }}
                                wrapperCol={{ span: 19 }}
                                name="icon"
                                label="图标"
                                rules={[{ required: nodetype !== 3 ? true : false, message: '请添加节点图标' }]}
                            >
                                <Input style={{width:'100%'}} placeholder="请选择或输入图标" />
                            </Form.Item>
                            
                            <Button type="primary" onClick={() => setVisible(true)}>选择图标</Button>
                        </Space.Compact>
                    </Col>
                </Row>
                <Row>
                    <Col span={8} >
                        <Form.Item
                            name="name"
                            label="名称"
                            rules={[{ required: true, message: '请添加节点名称' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            name="route_path"
                            label="路由"
                            rules={[{ required: nodetype !== 1 ? true : false, message: '请添加节点路由' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            name="component_path"
                            label="组件路径"
                            rules={[{ required: nodetype !== 1 ? true : false, message: '请添加组件路径' }]}
                        >
                            <Input disabled={nodetype !== 1 ? false : true} />
                        </Form.Item>
                    </Col>
                    
                </Row>
                <Row>
                    <Col span={8} >
                        <Form.Item
                            name="is_show"
                            label="是否展示"
                            rules={[{ required: true, message: '请选择是否展示' }]}
                        >
                            <Select>
                                <Option value={1}>是</Option>
                                <Option value={0}>否</Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            name="access_type"
                            label="访问类型"
                            rules={[{ required: true, message: '请选择访问类型' }]}
                        >
                            <Select>
                                <Option value={0}>开放</Option>
                                <Option value={1}>权限控制</Option>
                                {/* <Option value={2}>特殊处理</Option> */}
                            </Select>
                        </Form.Item>
                    </Col>
                </Row>
            </Modal>
            <Modal
                title="选择图标"
                open={visible}
                onCancel={() => setVisible(false)}
                okText="确认"
                cancelText="取消"
                onOk={() => {
                    form.setFieldsValue({ icon: selectedIcon })
                    setVisible(false);
                }}
                width={1200}
                destroyOnHidden
            >
                <IconPicker
                    // style={{ width: '100%' }}
                    value={selectedIcon}
                    onChange={selectIcon}
                />
            </Modal>
        </div>

    )
}

export default Menulist;